package controllers

import (
	"encoding/json"
	"errors"
	// "strconv"
	"qysoft/models"
	//	"fmt"
	"qysoft/libs/encrypt"
	"qysoft/libs/seaweed"
	//	"sys/common/log"
	// "reflect"
	"strings"
	"time"
	//	"reflect"
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/orm"
	"github.com/astaxie/beego/utils"
)

//UserController oprations for User
type UserController struct {
	CommonController
}

// URLMapping 方法映射
func (c *UserController) URLMapping() {
	c.Mapping("Post", c.Post)
	c.Mapping("GetOne", c.GetOne)
	c.Mapping("GetAll", c.GetAll)
	c.Mapping("Update", c.Update)
	c.Mapping("Delete", c.Delete)
	c.Mapping("UpdateUserProf", c.UpdateUserProf)
	//	c.Mapping("Logout", c.Logout)
	c.Mapping("Getme", c.Getme)
	c.Mapping("ChangePwd", c.ChangePwd)
	//	c.Mapping("UserStaticticsPage", c.UserStaticticsPage)
	//	c.Mapping("UserStatictics", c.UserStatictics)
	c.Mapping("GetAllOrgUsers", c.GetAllOrgUsers)
	//	c.Mapping("UserManager", c.UserManager)
	//	c.Mapping("GerUserByDept", c.GerUserByDept)
	c.Mapping("PhotoCancel", c.PhotoCancel)
	c.Mapping("GerUserByOrg", c.GerUserByOrg)

}

// UserJson 用户表单信息
type UserJson struct {
	Name         string `json:"Name"`
	Pname        string `json:"Pname"`
	RoleId       string `json:"RoleId"`
	Organization string `json:"Organization"`
	DeptId       string `json:"DeptId"`
	Status       int    `json:"Status"`
	Remark       string `json:"Remark"`
	Id           string `json:"Id"`
}

// Post create User
// @Title Post
// @Description create User
// @Param	body		body 	models.User	true		"body for User content"
// @Success 201 {int} models.User
// @Failure 403 body is empty
// @router / [post]
func (c *UserController) Post() {
	user := c.User
	var v models.User
	var u UserJson
	rdata, err := c.AesDecodeToByte(c.GetString("tdata"))
	if err != nil {
		c.RetError(ErrToken)
	}
	err = json.Unmarshal(rdata, &u)

	if err != nil {
		c.RetError(ErrToken)
	}

	if models.GetUserNameExist(u.Name) {
		c.RetError(ErrDupUser)
	}
	//	user对象

	// v.Name = name
	// oid := sdata["Organization"].(string)
	//	oid, _ := strconv.ParseInt(orgId, 10, 64)

	org, err := models.GetOrganizationById(u.Organization)
	if err != nil {
		c.RetError(ErrNoData)
	}
	v.Organization = org
	var dept *models.Dept

	dept, err = models.GetDeptById(u.DeptId)
	if err != nil {
		dept, err = models.GetDeptByName(org.Abbr, org.Id)
		if err != nil {
			c.RetError(ErrNoData)
		}
	}
	// v.Remark, _ = sdata["Remark"].(string)
	// vstatus, _ := sdata["Status"].(string)
	// v.Status, _ = strconv.Atoi(vstatus)
	pwd := beego.AppConfig.String("defaultsPwd")
	v.Pwd = encrypt.EncodeUserPwd(u.Name, pwd)
	v.Status = u.Status
	v.Salt = string(utils.RandomCreateBytes(10))
	v.Name = u.Name
	v.Abbr = u.Pname
	v.Isdelete = 0
	v.Ctime = time.Now()
	v.Creater = user.Name
	v.Utime = v.Ctime
	v.Updater = v.Creater
	v.Id = encrypt.GetGuid()
	//创建userrole对象
	//	var ur models.UserRole
	// rid := u.RoleId
	//	rid, _ := strconv.ParseInt(roleId, 10, 64)
	role, _ := models.GetRoleById(u.RoleId)
	//创建userdept对象
	// did := sdata["DeptId"].(string)
	beego.Debug(role.Name, dept.Name)

	// //	beego.Debug(roleId, dept)
	// if user.Organization.Id == u.Organization {
	// 	dept = *user.Dept[0]
	// }
	//	//创建userprof对象
	//	var up models.Userprof
	//	up.Type = 0
	//	up.Sex = 0
	//	up.Phone = ""
	//	up.Contact = ""
	//	up.Expert = ""
	//	up.Title = sdata["Pname"].(string)
	//	up.Job = ""
	//	up.Point = 0
	//	up.Photo = "default.jpg"
	//	up.Email = ""
	//	up.Logintime = time.Now()
	//	up.Loginip = ""
	//	up.Logincount = 0
	//	up.Remark = ""
	//	up.Isdelete = 0
	//	up.Ctime = time.Now()
	//	up.Creater = user.Name
	//	up.Utime = up.Ctime
	//	up.Updater = up.Creater

	//	beego.Debug(up.Title)
	_, err = models.CreateUser(&v, role.Id, dept.Id)
	if err != nil {
		beego.Debug(err)
		c.RetError(ErrInputData)
	}
	c.Dlog("添加了用户", v.Id)
	c.RetSuccess("ok")
}

// GetOne get User by id
// @Title Get
// @Description get User by id
// @Param	id		path 	string	true		"The key for staticblock"
// @Success 200 {object} models.User
// @Failure 403 :id is empty
// @router /:id [get]
func (c *UserController) GetOne() {
	id := c.GetString(":id")
	v, err := models.GetUserById(id)
	if err != nil {
		c.RetError(ErrNoData)
	}
	c.RetSuccess(v)
}

// GetAll get All User
// @Title Get All
// @Description get User
// @Param	query	query	string	false	"Filter. e.g. col1:v1,col2:v2 ..."
// @Param	fields	query	string	false	"Fields returned. e.g. col1,col2 ..."
// @Param	sortby	query	string	false	"Sorted-by fields. e.g. col1,col2 ..."
// @Param	order	query	string	false	"Order corresponding to each sortby field, if single value, apply to all sortby fields. e.g. desc,asc ..."
// @Param	limit	query	string	false	"Limit the size of result set. Must be an integer"
// @Param	offset	query	string	false	"Start position of result set. Must be an integer"
// @Success 200 {object} models.User
// @Failure 403
// @router / [get]
func (c *UserController) GetAll() {
	var fields []string
	var sortby []string
	var order []string
	query := make(map[string]interface{})
	var limit int64 = -1
	var offset int64

	// fields: col1,col2,entity.col3
	if v := c.GetString("fields"); v != "" {
		fields = strings.Split(v, ",")
	}
	// limit: 10 (default is 10)
	if v, err := c.GetInt64("limit"); err == nil {
		limit = v
	}
	// offset: 0 (default is 0)
	if v, err := c.GetInt64("offset"); err == nil {
		offset = v
	}
	// sortby: col1,col2
	if v := c.GetString("sortby"); v != "" {
		sortby = strings.Split(v, ",")
	}
	// order: desc,asc
	if v := c.GetString("order"); v != "" {
		order = strings.Split(v, ",")
	}
	// query: k:v,k:v
	if v := c.GetString("query"); v != "" {
		for _, cond := range strings.Split(v, ",") {
			kv := strings.SplitN(cond, ":", 2)
			if len(kv) != 2 {
				c.Data["json"] = errors.New("Error: invalid query key/value pair")
				c.ServeJSON()
				return
			}
			k, v := kv[0], kv[1]
			query[k] = v
		}
	}
	//	roleid := c.GetSession("roleinfo").(models.Role).Id

	l, _, err := models.GetAllUser(query, fields, sortby, order, offset, limit)
	if err != nil {
		beego.Error("err is :", err)
		c.RetError(ErrDatabase)
	}
	c.RetSuccess(l)

}

// Update update the User
// @Title Update
// @Description update the User
// @Param	id		path 	string	true		"The id you want to update"
// @Param	body		body 	models.User	true		"body for User content"
// @Success 200 {object} models.User
// @Failure 403 :id is not int
// @router /Update [post]
func (c *UserController) Update() {
	user := c.User
	// var v models.User
	var u UserJson
	rdata, err := c.AesDecodeToByte(c.GetString("tdata"))
	if err != nil {
		c.RetError(ErrToken)
	}
	err = json.Unmarshal(rdata, &u)

	if err != nil {
		c.RetError(ErrToken)
	}
	v, err := models.GetUserById(u.Id)
	if err != nil {
		c.RetError(ErrInputData)
	}
	ov := v
	// id := sdata["Id"].(string)
	//	id, _ := strconv.ParseInt(sid, 10, 64)
	// v, err := models.GetUserById(id)
	// if err != nil {
	// 	c.RetError(ErrInputData)
	// }
	// u := v
	//	orgId, _ := sdata["OrgId"].(string)
	//	oid, _ = strconv.ParseInt(orgId, 10, 64)
	//	org,_:=models.GetOrganizationById(oid)
	//	_, err = models.GetOrganizationById(v.Organization.Id)
	//	if err != nil {
	//		c.RetError(ErrInputData)
	//	}
	// beego.Debug(reflect.TypeOf(sdata["Status"]))
	// v.Remark, _ = sdata["Remark"].(string)
	// vstatus, _ := sdata["Status"].(float64)
	// v.Status = int(vstatus)
	// v.Id = u.Id
	v.Abbr = u.Pname
	v.Updater = user.Name
	v.Utime = time.Now()
	v.Abbr = u.Pname
	v.Remark = u.Remark
	// role, _ := models.GetRoleById(u.RoleId)

	// v.Role = role
	// dept, _ := models.GetDeptById(u.DeptId)
	// v.Dept = dept

	//	up, err := models.GetUserprofById(id)
	// if err != nil {
	// 	c.RetError(ErrInputData)
	// }
	//	up.Title = sdata["Pname"].(string)
	//	up.Updater = user.Name
	//	up.Utime = time.Now()
	// beego.Debug(rid)
	err = models.UpdateUser(v, u.RoleId, u.DeptId)
	if err != nil {
		c.RetError(ErrInvalidUser)
	}
	c.Dlog("修改用户", u.Id, 1, ov)
	c.RetSuccess("ok")
}

// UpdateUserProf 更新用户属性
// @Title Update
// @Description update the User
// @Param	id		path 	string	true		"The id you want to update"
// @Param	body		body 	models.User	true		"body for User content"
// @Success 200 {object} models.User
// @Failure 403 :id is not int
// @router /UpdateUserProf [post]
func (c *UserController) UpdateUserProf() {
	user := c.User
	// var v models.User
	var v models.User
	// beego.Debug("ta::::::::::", c.GetString("tdata"))
	rdata, err := c.AesDecodeToByte(c.GetString("tdata"))
	if err != nil {
		beego.Error(err)
		c.RetError(ErrInputData)
	}
	err = json.Unmarshal(rdata, &v)
	if err != nil {
		beego.Error(err)
		c.RetError(ErrInputData)
	}
	ov := v
	v.Updater = user.Name
	v.Utime = time.Now()
	err = models.UpdateUserProf(&v)
	if err != nil {
		c.RetError(ErrInvalidUser)
	}
	c.Dlog("修改用户", v.Id, 1, ov)
	c.RetSuccess("ok")
}

// Delete delete the User
// @Title Delete
// @Description delete the User
// @Param	id		path 	string	true		"The id you want to delete"
// @Success 200 {string} delete success!
// @Failure 403 id is empty
// @router /Delete [post]
func (c *UserController) Delete() {
	user := c.User
	rdata, err := c.AesDecode(c.GetString("tdata"))
	if err != nil {
		c.RetError(ErrToken)
	}
	sdata, _ := rdata.(map[string]interface{})
	id := sdata["Id"].(string)
	//	id, err := strconv.ParseInt(sid, 10, 64)
	err = models.SoftDeleteUser(id, user.Name)
	if err != nil {
		c.RetError(ErrDatabase)
	}
	c.Dlog("删除了用户", id)
	c.RetSuccess(id)
}

// Getme 获取用户自身数据
// @Title Getme
// @Description 获取用户自身数据
// @Success 200
// @Failure 403 :
// @router /Getme [get]
func (c *UserController) Getme() {
	user := c.User
	jdata := make(map[string]interface{})
	accessList := models.GetAccessTreeByRoleId(user.Role[0].Id)
	menu := make([]orm.Params, 0)
	if user.Role[0].Id == "1" {
		_, menu = models.GetAllResourceList(0)
	} else {
		menu, _ = models.GetResourceByRoleId(user.Role[0].Id, 0)
	}
	beego.Debug(len(menu))
	jdata["userinfo"] = user
	jdata["org"] = user.Organization
	jdata["dept"] = user.Dept[0]
	jdata["role"] = user.Role[0]
	jdata["accesslist"] = accessList
	jdata["menu"] = menu
	c.Dlog("登录系统，用户名为：", user.Id, 2)
	c.RetSuccess(jdata)

}

// ChangePwd 密码修改
// @Title ChangePwd
// @Description ChangePwd
// @Success 200
// @Failure 403 :
// @router /ChangePwd [post]
func (c *UserController) ChangePwd() {
	//	user := c.user
	rdata, err := c.AesDecode(c.GetString("tdata"))
	if err != nil {
		c.RetError(ErrToken)
	}
	sdata, _ := rdata.(map[string]interface{})
	oldPwd := sdata["oldPwd"].(string)
	newPwd := sdata["newPwd"].(string)
	repeatPwd := sdata["repeatPwd"].(string)
	beego.Debug(c.User.Name, oldPwd)
	if newPwd != repeatPwd {
		c.RetError(ErrInputData)
	}
	user, err := models.CheckLogin(c.User.Name, oldPwd)
	if err != nil {
		beego.Debug(err)
		c.RetError(ErrInputData)
	}
	p := encrypt.EncodeUserPwd(user.Salt, newPwd)
	user.Pwd = p
	err = models.UpdateUserById(user)
	if err != nil {
		c.RetError(ErrDatabase)
	}
	c.Dlog("修改密码", user.Id)
	c.RetSuccess(user.Id)
}

// DeleteUsers 删除用户列表
// @Title DeleteUsers
// @Description DeleteUsers
// @Success 200
// @Failure 403 :
// @router /DeleteUsers [post]
func (c *UserController) DeleteUsers() {
	user := c.User
	rdata, err := c.AesDecode(c.GetString("tdata"))
	if err != nil {
		c.RetError(ErrToken)
	}
	sdata, _ := rdata.([]interface{})
	for _, value := range sdata {
		id := value.(string)
		//		id, _ := strconv.ParseInt(eid, 10, 64)
		err := models.SoftDeleteUser(id, user.Name)
		if err != nil {
			c.RetError(ErrDatabase)
		}
		c.Dlog("删除了角色", id)
	}
	c.RetSuccess(sdata)
}

// ResetPwd 密码重置
// @Title ResetPwd
// @Description ResetPwd
// @Success 200
// @Failure 403 :
// @router /ResetPwd [post]
func (c *UserController) ResetPwd() {
	user := c.User
	rdata, err := c.AesDecode(c.GetString("tdata"))
	if err != nil {
		c.RetError(ErrToken)
	}
	sdata, _ := rdata.([]interface{})
	for _, value := range sdata {
		id := value.(string)
		//		id, _ := strconv.ParseInt(eid, 10, 64)
		v, err := models.GetUserById(id)
		v.Pwd = encrypt.EncodeUserPwd(v.Salt, beego.AppConfig.String("defaultsPwd"))
		v.Updater = user.Name
		v.Utime = time.Now()
		err = models.UpdateUserById(v)
		if err != nil {
			c.RetError(ErrDatabase)
		}
		c.Dlog("重置了用户密码", id)
	}
	c.RetSuccess("ok")
}

// GetAllOrgUsers 获取单位用户
// @Title GetAllOrgUsers
// @Description 获取单位用户
// @Success 200
// @Failure 403 :
// @router /GetAllOrgUsers [get]
func (c *UserController) GetAllOrgUsers() {
	user := c.User
	var fields []string
	var sortby []string
	var order []string
	var limit int64 = -1
	var offset int64
	query := make(map[string]interface{})
	tabledata := make(map[string]interface{})
	beego.Debug(user.Role[0].Type, user.Role[0].Name)
	switch user.Role[0].Type {
	case 2:
		query["Organization"] = user.Organization.Id
	case 3:
		ids := models.GetDeptChildrenStr(user.Dept[0].Id)
		beego.Debug(user.Dept[0].Id, ids)
		query["Dept__Dept__Id__in"] = *ids
	}
	//	query["Organization"] = strconv.FormatInt(orgId, 10)
	l, count, err := models.GetAllUser(query, fields, sortby, order, offset, limit)
	if err != nil {
		beego.Error("err is :", err)
		c.RetError(ErrDatabase)
	}
	//	beego.Error("count is :", count, l)
	tabledata["total"] = count
	tabledata["tabledata"] = l
	c.RetSuccess(l)

}

// GerUserByOrg 根据单位获取人员穿梭表
// @Title GerUserByOrg
// @Description 根据单位获取人员穿梭表
// @Success 200
// @Failure 403 :
// @router /GerUserByOrg [get]
func (c *UserController) GerUserByOrg() {
	user := c.User
	//	deptId, _ := c.GetInt64("DeptId")
	datas, err := models.GetUserByOrg(user.Organization.Id)
	if err != nil {
		beego.Error(err)
		c.RetError(ErrNoData)
	}
	c.RetSuccess(datas)

}

// @Title PhotoCancel
// @Description PhotoCancel取消上传文件
// @Success PhotoCancel success!
// @Failure
// @router /PhotoCancel [post]
func (c *UserController) PhotoCancel() {

	rdata, err := c.AesDecode(c.GetString("tdata"))
	if err != nil {
		c.RetError(ErrToken)
	}
	sdata, _ := rdata.(map[string]interface{})
	url := sdata["Url"].(string)
	//	var path string
	//	//	os.Remove("/data/root/" + Url)
	//	if ostype == "windows" {
	//		//		url = path
	//		path = /*"c:\\tgo\\src\\ilive\\" +*/ url
	//	} else if ostype == "linux" {
	//		path = "/data/root/" + url
	//	}

	//	beego.Debug(path)
	//	os.Remove(url)
	seaweed.DeleteFile(url)
	c.RetSuccess(url)

	//	c.RetSuccess(v)

}
